﻿using System;
using System.Collections.Generic;
using System.Web.Services;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using Adex;
using Telerik.Web.UI;
using MediaMonitor.Common;
using System.Web.Security;
using System.Configuration;
using System.Drawing;
using Telerik.Charting;
using System.Transactions;
using SubSonic;
using System.Net.Mail;
using System.Collections;

namespace MediaMonitor.Users
{
    public partial class NewAll_newsalert_Filter : Adex.BasePage
    {

        DateTime sDate = DateTime.MinValue, eDate = DateTime.MinValue;
        private int mediaTypeCode = 0;
        private string mediaCodes = "";
        string mediaTypeName = "";
        string AdvertiserName = "";
        string AdvertiserMake = "";
        string NewsTitle = "";
        string Calification = "";
        string reportUrl = "";
        bool TitleNews;
        bool Summary;
        bool Text;
        string mediaTypeNameMake = "";
        string TV = "";
        string Radio = "";
        string Internet = "";
        string Press = "";
        string InMedia = "";
        string Code = "";
        string days = "";
        string Importancia = string.Empty;
        protected void Page_Load(object sender, EventArgs e)
        {
            hdnDate.Value = lblSelectedFromDate.Text;
            if (Request.Cookies["User"]["UserID"].ToString() == null || Request.Cookies["User"]["Company"] == null || Request.Cookies["User"]["CompanyCode"].ToString() == null)
                Response.Redirect("../logout.aspx");
            if (!IsPostBack)
            {
               
               
                Utility.AddDateControlToPage(this.Page);
                SetCalendarDates();
                FillMediaTypes();
                FillAdvertisers();
                if (Request.QueryString["Code"].ToString() != "")
                {
                    switch (Request.QueryString["Code"].ToString())
                    {
                        case "Tv":
                            chkNewsMediaType.SelectedValue = "1";
                            Response.Cookies["Code"].Value = Request.QueryString["Code"].ToString();
                            Response.Cookies["Code"].Expires = DateTime.Now.AddDays(1);
                            break;
                        case "Radio":
                            chkNewsMediaType.SelectedValue = "3";
                            Response.Cookies["Code"].Value = Request.QueryString["Code"].ToString();
                            Response.Cookies["Code"].Expires = DateTime.Now.AddDays(1);
                            break;
                        case "Press":
                            chkNewsMediaType.SelectedValue = "6";
                            Response.Cookies["Code"].Value = Request.QueryString["Code"].ToString();
                            Response.Cookies["Code"].Expires = DateTime.Now.AddDays(1);
                            break;
                        case "Internet":
                            chkNewsMediaType.SelectedValue = "9";
                            Response.Cookies["Code"].Value = Request.QueryString["Code"].ToString();
                            Response.Cookies["Code"].Expires = DateTime.Now.AddDays(1);
                            break;
                        case "All":
                            chkNewsMediaType.SelectedValue = "0";
                            Response.Cookies["Code"].Value = "media";
                            Response.Cookies["Code"].Expires = DateTime.Now.AddDays(1);
                            break;
                    }
                }
            }
        }

        private void SetCalendarDates()
        {


            DataTable dt = TblNewsAlert.Query().DISTINCT().SetSelectList("RFDate").ExecuteDataSet().Tables[0];


            foreach (DataRow dr in dt.Rows)
            {

                RadCalendarDay d1 = new RadCalendarDay(calS);
                d1.Date = Utility.ToDateTime(dr["RFDate"]);
                d1.IsDisabled = false;
                d1.IsSelectable = true;

                d1.ItemStyle.BackColor = System.Drawing.Color.PowderBlue;
                d1.ItemStyle.ForeColor = System.Drawing.Color.White;

                calS.SpecialDays.Add(d1);

                RadCalendarDay d2 = new RadCalendarDay(calE);
                d2.Date = Utility.ToDateTime(dr["RFDate"]);
                d2.IsDisabled = false;
                d2.IsSelectable = true;

                d2.ItemStyle.BackColor = System.Drawing.Color.PowderBlue;
                d2.ItemStyle.ForeColor = System.Drawing.Color.White;


                calE.SpecialDays.Add(d2);
            }



        }
        private static DataSet GetLookupDataSet()
        {
            //dsLookUpByUser_IN_
            if (HttpContext.Current.Cache["dsLookUpByUser_NC_" + AppUser.CurrUserID.ToString()] == null)
            {
                //Get Lookup Tables filtered by User / Company settings
                DataSet ds = SPs.GetLookupTables(AppUser.CurrUserID, "NC").GetDataSet();
                ds.Tables[0].TableName = "MediaType";
                ds.Tables[1].TableName = "Media";
                ds.Tables[2].TableName = "Agency";
                ds.Tables[3].TableName = "Advertiser";
                ds.Tables[4].TableName = "Brand";
                ds.Tables[5].TableName = "Sector";
                ds.Tables[6].TableName = "SubSector";
                ds.Tables[7].TableName = "Category";
                ds.Tables[8].TableName = "Product";
                ds.Tables[9].TableName = "ProdVersion";

                HttpContext.Current.Cache.Insert("dsLookUpByUser_NC_" + AppUser.CurrUserID.ToString(), ds, null, DateTime.Now.AddMinutes(60), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, null);
                return ds;

            }
            else
            {
                return ((DataSet)(HttpContext.Current.Cache["dsLookUpByUser_NC_" + AppUser.CurrUserID.ToString()]));
            }
        }

        #region Fill Media

        private void FillMediaTypes()
        {
            ReportFuncs objReportFuncs = new ReportFuncs();
            DataTable dt = objReportFuncs.GETMediaTypeNameFORNewsAlert();
            chkNewsMediaType.DataSource = dt;
            chkNewsMediaType.DataBind();

        }

        private void FillMedia(int MediaTypeCode)
        {
            ReportFuncs objReportFuncs = new ReportFuncs();
            DataTable dt = objReportFuncs.GETMediaNameFORNewsAlert(MediaTypeCode);
            lstMedia.DataSource = dt;
            lstMedia.DataBind();
        }


        protected void chkNewsMediaType_SelectedIndexChanged(object sender, EventArgs e)
        {

            if (chkNewsMediaType.SelectedItem != null)
            {
                FillMedia(Utility.ToInt(chkNewsMediaType.SelectedValue));

                if (!chkAllMedia.Checked)
                    chkAllMedia.Checked = true;

                chkAllMedia_Changed(sender, e);
                FillAdvertisers();
                lblSelectedFromDate.Text = lblSelectedFromDate.Text;
            }
        }
        protected void chkAllMedia_Changed(object sender, EventArgs e)
        {
            if (!chkAllMedia.Checked)
                panelMediaList.Visible = true;
            else
                panelMediaList.Visible = false;
            pnlUpdate_Media1.Update();
        }


        #endregion


        #region FillLists

        public DataTable RemoveDuplicateRows(DataTable dTable, string colName)
        {
            Hashtable hTable = new Hashtable();
            ArrayList duplicateList = new ArrayList();

            //Add list of all the unique item value to hashtable, which stores combination of key, value pair.
            //And add duplicate item value in arraylist.
            foreach (DataRow drow in dTable.Rows)
            {
                if (hTable.Contains(drow[colName]))
                    duplicateList.Add(drow);
                else
                    hTable.Add(drow[colName], string.Empty);
            }

            //Removing a list of duplicate items from datatable.
            foreach (DataRow dRow in duplicateList)
                dTable.Rows.Remove(dRow);

            //Datatable which contains unique records will be return as output.
            return dTable;
        }
        private void FillAdvertisers()
        {
            ReportFuncs objReportFuncs = new ReportFuncs();
            DataTable dt = objReportFuncs.GETAdvertiserFORNewsAlert(Convert.ToInt32(Request.Cookies["User"]["CompanyCode"].ToString()));


            lstAdvertiser.DataSource = dt;
            lstAdvertiser.DataBind();

            lstAdvertiser.Items.Insert(0, new System.Web.UI.WebControls.ListItem("- ALL -", "0"));
        }
        //private void FillCategories()
        //{
        //    DataTable dt = GetLookupDataSet().Tables[7];

        //    string filter = "1=1";
        //    switch (lstMediaType.SelectedValue)
        //    {
        //        case "1":
        //            {
        //                filter += " AND MediaType='TVCR' AND TV = 1";
        //                break;
        //            }

        //        case "3":
        //            {
        //                filter += " AND MediaType='TVCR' AND RD = 1";
        //                break;
        //            }
        //        case "5":
        //            {
        //                filter += " AND MediaType='TVCR' AND CB = 1";
        //                break;
        //            }
        //        case "6":
        //            {
        //                filter += " AND MediaType='PR' AND PR = 1";
        //                break;
        //            }
        //        case "7":
        //            {
        //                filter += " AND MediaType='OD' AND OD = 1";
        //                break;
        //            }
        //        case "8":
        //            {
        //                filter += " AND MediaType='NS' AND NS = 1";
        //                break;
        //            }
        //    }

        //    // filter += lstSector.SelectedValue != "0" ? " AND SectorCode=" + lstSector.SelectedValue : "";
        //    filter += lstSubSector.SelectedValue != "0" ? " AND SubSectorID=" + lstSubSector.SelectedValue : "";

        //    string sort = "CategoryName";

        //    DataView dv = new DataView(dt, filter, sort, DataViewRowState.OriginalRows);

        //    DataTable dtcolumns = dv.ToTable(true, "CategoryID", "CategoryName");

        //    if (dtcolumns.Rows.Count > 0)
        //    {
        //        dtcolumns = RemoveDuplicateRows(dtcolumns, "CategoryName");
        //        lstCategory.DataSource = dtcolumns;
        //        lstCategory.DataBind();
        //    }
        //    lstCategory.Items.Insert(0, new ListItem("- ALL -", "0"));
        //}

        #endregion

        #region AutoComplete Functions
        [WebMethod]
        public static string[] AutoComplete_FillProduct(string prefixText, int count, string contextKey)
        {
            //contextKey is brandCode


            string filter = "1=1 ";
            filter += " AND MediaType='NS' AND ProductName LIKE '" + prefixText + "%'";

            //get brand 

            if (contextKey != null && contextKey != "" && contextKey != "0")
            {
                filter += " AND BrandID = " + contextKey;
            }

            if (count == 0) { count = 10; }
            List<string> items = new List<string>(count);

            DataTable dt = GetLookupDataSet().Tables[8];

            DataRow[] drs = dt.Select(filter);

            int counter = 0;
            foreach (DataRow dr in drs)
            {
                items.Add(AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(dr["ProductName"].ToString(), dr["ProductID"].ToString()));


                if (++counter >= count) { break; }
            }

            return items.ToArray();
        }
        #endregion

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            bool tmp1 = DateTime.TryParse(calS.SelectedDate.ToShortDateString(), out sDate);
            bool tmp2 = DateTime.TryParse(calE.SelectedDate.ToShortDateString(), out eDate);

            if (sDate < Utility.ToDateTime("01/01/2000"))         //Calendar Start Date
                sDate = Utility.ToDateTime("01/01/2000");

            if (eDate < Utility.ToDateTime("01/01/2000"))        //Calendar End Date
                eDate = Utility.ToDateTime("01/01/2000");

            //mediaTypeCode = Utility.ToInt(lstNewsMediaType.SelectedValue);


            if ((sDate.ToString() != "01/01/2000 12:00:00 AM") && (eDate.ToString() != "01/01/2000 12:00:00 AM"))
            {



                //if (Utility.ToStr(chkNewsMediaType.SelectedValue) == null)
                //    mediaTypeName = "";
                //else
                //    mediaTypeName = Utility.ToStr(chkNewsMediaType.SelectedItem.Text);
                ReportFuncs objReportFuncs = new ReportFuncs();
                if (Utility.ToStr(lstAdvertiser.SelectedValue) == "0")
                {
                    DataTable dt = objReportFuncs.GETAdvertiserFORNewsAlert(Convert.ToInt32(Request.Cookies["User"]["CompanyCode"].ToString()));
                    if (dt.Rows.Count != 0)
                    {
                        for (int i = 1; i <= dt.Rows.Count; i++)
                        {
                            AdvertiserName += dt.Rows[i - 1]["AdvertiserName"] + ",";
                            AdvertiserMake += "'" + dt.Rows[i - 1]["AdvertiserName"] + "',";
                        }
                        AdvertiserName = AdvertiserName.ToString().TrimEnd(',');
                        AdvertiserMake = AdvertiserMake.ToString().TrimEnd(',');
                    }
                    else
                        AdvertiserMake = "''";
                }
                else
                {
                    AdvertiserName = Utility.ToStr(lstAdvertiser.SelectedItem.Text);
                    AdvertiserMake = "'" + Utility.ToStr(lstAdvertiser.SelectedItem.Text) + "'";
                }

                NewsTitle = Utility.ToStr(txtNewsTitle.Text);
                if (Utility.ToStr(lstNewsType.SelectedValue) == "0")
                    Calification = "";
                else
                    Calification = Utility.ToStr(lstNewsType.SelectedItem.Text);

                
                //}
                TitleNews = chkTitle.Checked;
                Summary = chkSummary.Checked;
                Text = chkText.Checked;
                
                
                if (!chkMediaAll.Checked)
                {
                    if (chkNewsMediaType.SelectedItem != null)
                    {
                        foreach (System.Web.UI.WebControls.ListItem objItem in chkNewsMediaType.Items)
                        {
                            if (objItem.Selected)
                            {
                                mediaTypeName += objItem.Text + ",";
                                mediaTypeNameMake += "'" + objItem.Text + "',";
                                switch (objItem.Text)
                                {
                                    case "TV":
                                        TV = "TV";
                                        Response.Cookies["Last"]["TV"] = "TV";
                                        break;
                                    case "Radio":
                                        Response.Cookies["Last"]["Radio"] = "Radio";
                                        Radio = "Radio";
                                        break;
                                    case "Internet":
                                        Internet = "Internet";
                                        Response.Cookies["Last"]["Internet"] = "Internet";
                                        break;
                                    case "Press":
                                         Response.Cookies["Last"]["Press"] = "Press";
                                         Press = "Press";
                                        break;

                                }
                            }
                        }
                        mediaTypeName = mediaTypeName.TrimEnd(',');
                        mediaTypeNameMake = mediaTypeNameMake.TrimEnd(',');
                        Code = "";
                        if (mediaTypeName.Contains(","))
                        { 
                        reportUrl = "NewAll-newsalertSearchMultiMedia.aspx";
                        }
                        else
                            reportUrl = "NewAll-newsalertSearch.aspx";
                            
                    }
                    else
                    {
                        string script = "alert(\"Please select atleast one News media type \");";
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "ServerControlScript", script, true);
                        return;
                    }

                }
                else
                {
                    mediaTypeName = "";
                    mediaTypeNameMake = "";
                    Code = "search";
                    Response.Cookies["Last"]["TV"] = "TV";
                    Response.Cookies["Last"]["Radio"] = "Radio";
                    Response.Cookies["Last"]["Press"] = "Press";
                    Response.Cookies["Last"]["Internet"] = "Internet";
                    reportUrl = "NewAll-newsalertSearchMultiMedia.aspx";
                }//mediaCodes = Utility.ToInt(lstMedia.SelectedValue).ToString();
                if (mediaTypeName != "")
                {
                    foreach (System.Web.UI.WebControls.ListItem itm in lstMedia.Items)
                    {
                        if (itm.Selected)
                            mediaCodes += itm.Value + ",";
                    }
                    mediaCodes = mediaCodes.TrimEnd(',');
                }
                else
                    mediaCodes = "";
                foreach (System.Web.UI.WebControls.ListItem itm in chklstDays.Items)
                {
                    if (itm.Selected)
                        days += itm.Value + ",";
                }
                foreach (System.Web.UI.WebControls.ListItem itm in lstImportancia.Items)
                {
                    if (itm.Selected)
                    {
                        if (itm.Value != "0")
                            Importancia = itm.Value;
                    }
                }
                // DataTable dtToday = SPs.NewsAlertcountforSearch(sDate.ToShortDateString() + " 00:00:00.000", eDate.ToShortDateString() + " 23:59:59.999", NewsTitle, AdvertiserName, Calification, mediaTypeName, mediaCodes, AdvertiserMake, Convert.ToBoolean(TitleNews), Convert.ToBoolean(Summary), Convert.ToBoolean(Text), "", Code, TV, Radio, Internet, Press, mediaTypeNameMake).GetDataSet().Tables[0];
                DataTable dtt = SPs.GetReportNewsAlertSearch(sDate.ToShortDateString() + " 00:00:00.000", eDate.ToShortDateString() + " 23:59:59.999", NewsTitle, AdvertiserName, Calification, mediaTypeName, mediaCodes, AdvertiserMake, TitleNews, Summary, Text, "", mediaTypeNameMake, days.TrimEnd(','), Convert.ToInt32(Request.Cookies["User"]["UserID"].ToString()), Importancia).GetDataSet().Tables[1];
                if (dtt.Rows.Count > 0)
                {
                    Response.Redirect(
                          Server.UrlPathEncode(string.Format(reportUrl + "?sd={0}&title={1}&Advertiser={2}&Calification={3}&NewsType={4}&ed={5}&TitleNews={6}&Summary={7}&Text={8}&mediaCode={9}&AdvertiserMake={10}&mediaTypeNameMake={11}&TV={12}&Radio={13}&Internet={14}&Press={15}&Code={16}&days={17}&Importancia={18}", sDate.ToShortDateString().Replace("/", "_"), NewsTitle, AdvertiserName, Calification, mediaTypeName, eDate.ToShortDateString().Replace("/", "_"), TitleNews.ToString(), Summary.ToString(), Text.ToString(), mediaCodes, AdvertiserMake, mediaTypeNameMake, TV, Radio, Internet, Press, Code, days.TrimEnd(','), Importancia)));
                }
                else
                {
                    string script = "alert(\"No Record Found For Your Search!\");";
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "ServerControlScript", script, true);

                }
            }
            else
            {
                string script = "alert(\"Please select date first!\");";
                ScriptManager.RegisterStartupScript(this, this.GetType(), "ServerControlScript", script, true);
            }
        }



    }
  
      
}
